<?php

namespace app\service;

use app\model\User;
use app\model\UserFinancialRecord;
use app\model\UserPosition;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use Tinywan\Jwt\JwtToken;

class UserService extends BaseService
{

    const STATUS_NORMAL = 1;        //用户状态 正常
    const STATUS_DISABLE = 2;       //用户状态 停用

    //登录
    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function toLoginByCode($code, $platform): array
    {

        $userModel = new User();
        //获取微信小程序的openid
        if ($platform) {
            $open_id = $this->get_open_id($code);
        } else {
            $open_id = $code;
        }
        //查询会员信息
        $userInfo = $userModel->where(['open_id' => $open_id])->find();
        if (empty($userInfo)) {
            //注册
            $param = [
                'open_id' => $open_id,
                'nickname' => $data['username'] ?? 'wx_' . rand(1000, 10000),
                'avatar' => $data['avatar'] ?? '',
                'platform' => $platform,
                'status' => self::STATUS_NORMAL,
            ];

            $id = $userModel->insertGetId($param);
            if (!$id) {
                return $this->returnFail('注册失败');
            }
            //注册成功
            $userInfo = $userModel->where(['id' => $id])->find();

            //初始化地块
            (new UserPositionService())->initPosition($id);

        }
        if ($userInfo['status'] == self::STATUS_DISABLE) {
            return $this->returnFail('该账号已停用');
        }

        $extend = [
            'id' => $userInfo['id'],
            'name' => 'DWYS',
            'access_exp' => 8640000,  // 100天
            'refresh_exp' => 8640000,  // 100天
            'client' => JwtToken::TOKEN_CLIENT_MOBILE
        ];
        $generateToken = JwtToken::generateToken($extend);

        if ($generateToken) {
            $data = ['token' => $generateToken['access_token'], 'user_info' => $userInfo];
            return $this->returnSuccess($data);
        }
        return $this->returnFail('失败');

    }


    //获取用户信息
    public function get_user_info($user_id): array
    {
        $userModel = new User();
        return $userModel->where('id', $user_id)->find()->toArray();
    }


    //获取微信小程序的openid
    protected function get_open_id($js_code)
    {
        $appid = config('wx.appId');
        $secret = config('wx.appSecret');
        $logsList = http_get(config('wx.code2SessionUrl') . '?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $js_code . '&grant_type=authorization_code');
        return json_decode($logsList);
    }


    //更改余额
    public function change_money($user_id, $money, $type = 0, $status = 0): array
    {
        if ($money <= 0) {
            return $this->returnFail('金额错误');
        }

        switch ($type) {
            case USER_CAPITAL_TYPE['金币']:
                $field = USER_CAPITAL_TYPE_MAP['金币'];
                break;
            case USER_CAPITAL_TYPE['积分']:
                $field = USER_CAPITAL_TYPE_MAP['积分'];
                break;
            case USER_CAPITAL_TYPE['钻石']:
                $field = USER_CAPITAL_TYPE_MAP['钻石'];
                break;
            case USER_CAPITAL_TYPE['至臻点']:
                $field = USER_CAPITAL_TYPE_MAP['至臻点'];
                break;
            default:
                return $this->returnFail('类型参数错误');
        }


        try {
            $user = (new User())->where('id', $user_id)->find();
            if (!$user) {
                return $this->returnFail('用户不存在');
            }
            $before_capital =  $user->$field;

            switch ($status) {
                case USER_CAPITAL_STATUS['增加']:
                    //增加金币
                    $user->$field = $user->$field + $money;
                    $up_res = $user->save();
                    if (!$up_res) {
                        return $this->returnFail('增加金币失败');
                    }
                    break;
                case  USER_CAPITAL_STATUS['扣除']:
                    //扣除金币
                    if ($user->$field < abs($money)) {
                        return $this->returnFail('金币不足');
                    }
                    $user->$field = $user->$field - $money;
                    $up_res = $user->save();
                    if (!$up_res) {
                        return $this->returnFail('扣除金币失败');
                    }
                    break;
                default:
                    return $this->returnFail('状态参数错误');
            }
            $after_capital =  $user->$field;

            //记录资金变动到数据库
            $user_financial_record = new UserFinancialRecord();
            $user_financial_record->user_id = $user_id;
            $user_financial_record->type = $type;
            $user_financial_record->status = $status;
            $user_financial_record->money = $money;
            $user_financial_record->before_money = $before_capital;
            $user_financial_record->after_money = $after_capital;
            $res = $user_financial_record->save();
            if (!$res) {
                return $this->returnFail('记录资金变动失败');
            }
            //返回当前金币
            return $this->returnSuccess($user->$field);
        } catch (DbException $e) {
            return $this->returnFail($e->getMessage());
        }

    }




    /**
     * 更改工人
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function change_worker($user_id, $type = 0): array
    {
        $user = (new User())->where('id',$user_id)->find();
        if (!$user){
            return $this->returnFail('用户不存在');
        }
        switch ($type){
            case FACTORY_WORKER['休息']:
                $user->worker = $user->worker + 1;
                break;
            case FACTORY_WORKER['工作']:
                if ($user->worker <= 0){
                    return $this->returnFail('工人数量不足');
                }
                $user->worker = $user->worker - 1;
                break;
            default:
                return $this->returnFail('类型参数错误');
        }
        $res = $user->save();
        if (!$res){
            return $this->returnFail('更改工人失败');
        }
        return $this->returnSuccess($user->worker);

    }


}